package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Permission;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/permission/*")
public class PermissionServlet extends BaseServlet {

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前页
        String pageNum = req.getParameter("pageNum");

        List<Permission> list = permissionService.findAll(pageNum);

        //创建pageInfo对象
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        //将pageInfo添加到请求域中
        req.setAttribute("page", pageInfo);
        //请求转发到显示权限资源信息页面
        req.getRequestDispatcher("/pages/permission-list.jsp").forward(req, resp);
    }

/*    //跳转添加权限资源信息方法
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/pages/permission/add.jsp").forward(req, resp);
    }*/

    //添加功能
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过工具类来封装新建的权限资源信息为权限资源对象
        Permission permission = BeanUtil.fillBean(req, Permission.class);
        //通过业务层来调用方法添加权限资源信息
        boolean flag = permissionService.add(permission);

        if (flag) {
            findAll(req, resp);
        } else {
//            resp.sendRedirect("/error.jsp");
        }
    }


    //跳转编辑权限资源信息方法
    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据id来获取权限信息的id
        String id = req.getParameter("id");
        //根据id来查询企业信息
        Permission permission = permissionService.findById(id);
        req.setAttribute("permission", permission);
        req.getRequestDispatcher("/pages/permission-update.jsp").forward(req, resp);
    }

    public void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Permission permission = BeanUtil.fillBean(req, Permission.class);
        boolean flag = permissionService.edit(permission);

        if (flag) {
            findAll(req, resp);
        } else {
//            req.getRequestDispatcher("/error.jsp").forward(req, resp);
//            resp.sendRedirect("/error.jsp")
        }
    }

    //删除功能
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ids = req.getParameter("id");
        String[] id = ids.split(",");

        boolean flag = permissionService.deleteByIds(id);
        if (flag) {
            findAll(req, resp);
        } else {
//            resp.sendRedirect("/error.jsp");
        }
    }
}
